package org.dromara.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.erp.domain.ErpAssetCategory;
import org.dromara.erp.mapper.ErpAssetCategoryMapper;
import org.dromara.erp.service.IErpAssetCategoryService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 资产分类Service业务层处理
 *
 * @author Mr Lei
 * @date 2024-06-01
 */
@RequiredArgsConstructor
@Service
public class ErpAssetCategoryServiceImpl implements IErpAssetCategoryService {

    private final ErpAssetCategoryMapper baseMapper;

    /**
     * 查询资产分类
     */
    @Override
    public ErpAssetCategory queryById(Long id){
        return baseMapper.selectById(id);
    }


    /**
     * 查询资产分类列表
     */
    @Override
    public List<ErpAssetCategory> queryList(ErpAssetCategory bo) {
        LambdaQueryWrapper<ErpAssetCategory> lqw = buildQueryWrapper(bo);
        return baseMapper.selectList(lqw);
    }

    private LambdaQueryWrapper<ErpAssetCategory> buildQueryWrapper(ErpAssetCategory bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpAssetCategory> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getParentId() != null, ErpAssetCategory::getParentId, bo.getParentId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), ErpAssetCategory::getName, bo.getName());
        return lqw;
    }

    /**
     * 新增资产分类
     */
    @Override
    public Boolean insertByBo(ErpAssetCategory bo) {
        ErpAssetCategory add = MapstructUtils.convert(bo, ErpAssetCategory.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改资产分类
     */
    @Override
    public Boolean updateByBo(ErpAssetCategory bo) {
        ErpAssetCategory update = MapstructUtils.convert(bo, ErpAssetCategory.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpAssetCategory entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除资产分类
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
